import React, { useEffect, useRef, useState } from "react";
import Lenis from "@studio-freight/lenis";
import styles from "./index.module.scss";

export interface ScrollEvent {
  progress: number; // 滚动进度 (0-1)
  direction: number; // 滚动方向 (1: 向下, -1: 向上)
  velocity: number; // 滚动速度
  scrollY: number; // 当前滚动位置
  limit: number; // 最大滚动距离
}

interface ScrollViewProps {
  onScroll?: (event: ScrollEvent) => void;
  onScrollStart?: () => void;
  onScrollEnd?: () => void;
  children?: React.ReactNode;
}

const ScrollView: React.FC<ScrollViewProps> = ({
  onScroll,
  onScrollStart,
  onScrollEnd,
  children,
}) => {
  const lenisRef = useRef<Lenis | null>(null);
  const [isScrolling, setIsScrolling] = useState(false);
  const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // 初始化 Lenis
    lenisRef.current = new Lenis({
      duration: 1.4,
      easing: i => Math.min(1, 1.001 - Math.pow(2, -10 * i)),
      smoothWheel: true,
      wheelMultiplier: 0.8,
      orientation: "vertical",
      gestureOrientation: 'vertical',
      // direction: "vertical",
    });

    // 监听滚动事件
    lenisRef.current.on("scroll", (e: any) => {
      const scrollEvent: ScrollEvent = {
        progress: e.progress,
        direction: e.direction,
        velocity: e.velocity,
        scrollY: e.scroll,
        limit: e.limit,
      };

      // 抛出滚动事件
      if (onScroll) {
        onScroll(scrollEvent);
      }

      // 处理滚动开始事件
      if (!isScrolling) {
        setIsScrolling(true);
        if (onScrollStart) {
          onScrollStart();
        }
      }

      // 清除之前的定时器
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }

      // 设置滚动结束检测
      scrollTimeoutRef.current = setTimeout(() => {
        setIsScrolling(false);
        if (onScrollEnd) {
          onScrollEnd();
        }
      }, 150); // 150ms 后认为滚动结束
    });

    // 更新动画帧
    function raf(time: number) {
      lenisRef.current?.raf(time);
      requestAnimationFrame(raf);
    }
    requestAnimationFrame(raf);

    // 组件卸载时清理
    return () => {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
      if (lenisRef.current) {
        lenisRef.current.destroy();
      }
    };
  }, [onScroll, onScrollStart, onScrollEnd, isScrolling]);

  return <div className={styles.scrollView}>{children}</div>;
};

export default ScrollView;
